{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  一个简单的两层神经网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "[2051] 60000 28 28\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "[2051] 10000 28 28\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "mnist = input_data.read_data_sets('data/',one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ready\n"
     ]
    }
   ],
   "source": [
    "n_hidden_1 = 256\n",
    "n_hidden_2 = 128\n",
    "n_input = 784\n",
    "n_classes = 10\n",
    "\n",
    "# inputs outputs\n",
    "x = tf.placeholder('float',[None,n_input])\n",
    "y = tf.placeholder('float',[None,n_classes])\n",
    "\n",
    "# network params\n",
    "stddev = 0.1\n",
    "# 权重 input->layer1->layer2->out\n",
    "weights = {\n",
    "    'w1': tf.Variable(tf.random_normal([n_input,n_hidden_1],stddev=stddev)),\n",
    "    'w2': tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2],stddev=stddev)),\n",
    "    'out':tf.Variable(tf.random_normal([n_hidden_2,n_classes],stddev=stddev))\n",
    "}\n",
    "\n",
    "# bias\n",
    "biases = {\n",
    "    'b1':tf.Variable(tf.zeros([n_hidden_1])),\n",
    "    'b2':tf.Variable(tf.zeros([n_hidden_2])),\n",
    "    'out_bias':tf.Variable(tf.zeros([n_classes]))\n",
    "    \n",
    "}\n",
    "print('ready')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "function done\n"
     ]
    }
   ],
   "source": [
    "def forward(_X,_weights,_biases):\n",
    "    layer_1 = tf.nn.relu(tf.add(tf.matmul(_X,_weights['w1']),_biases['b1']))\n",
    "    layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1,_weights['w2']),_biases['b2']))\n",
    "    out = tf.add(tf.matmul(layer_2,_weights['out']),_biases['out_bias'])\n",
    "    return out\n",
    "print('function done')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-6-7fa5a510deab>:5: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#预测\n",
    "pred = forward(x,weights,biases)\n",
    "\n",
    "# loss函数 与 反向梯度下降\n",
    "loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))\n",
    "optm = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)\n",
    "check_correct = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))\n",
    "acc = tf.reduce_mean(tf.cast(check_correct,'float'))\n",
    "\n",
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<input_data.read_data_sets.<locals>.DataSets object at 0x000001E6E5014E48>\n"
     ]
    }
   ],
   "source": [
    "print(mnist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch:000/020 loss:00.968485\n",
      "train acc:0.870000\n",
      "test acc:0.868300\n",
      "epoch:001/020 loss:00.417175\n",
      "train acc:0.890000\n",
      "test acc:0.898200\n",
      "epoch:002/020 loss:00.336821\n",
      "train acc:0.900000\n",
      "test acc:0.912900\n",
      "epoch:007/020 loss:00.220029\n",
      "train acc:0.940000\n",
      "test acc:0.935900\n",
      "epoch:008/020 loss:00.208011\n",
      "train acc:0.960000\n",
      "test acc:0.938000\n",
      "epoch:009/020 loss:00.197386\n",
      "train acc:0.940000\n",
      "test acc:0.938900\n",
      "epoch:010/020 loss:00.188068\n",
      "train acc:0.930000\n",
      "test acc:0.943000\n",
      "epoch:015/020 loss:00.151951\n",
      "train acc:0.980000\n",
      "test acc:0.951000\n",
      "epoch:016/020 loss:00.146002\n",
      "train acc:0.950000\n",
      "test acc:0.951300\n",
      "epoch:017/020 loss:00.140900\n",
      "train acc:0.940000\n",
      "test acc:0.953600\n",
      "epoch:018/020 loss:00.135966\n",
      "train acc:0.960000\n",
      "test acc:0.954900\n",
      "finish\n"
     ]
    }
   ],
   "source": [
    "epochs = 20\n",
    "batch_size = 100\n",
    "display_step = 4\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    # 优化：\n",
    "    for epoch in range(epochs):\n",
    "        avg_cost = 0\n",
    "        total_batch = int(mnist.train.num_examples/batch_size)\n",
    "        for i in range(total_batch):\n",
    "            batch_xs,batch_ys = mnist.train.next_batch(batch_size=batch_size)\n",
    "            feeds = {x:batch_xs,y:batch_ys}\n",
    "            sess.run(optm,feed_dict=feeds)\n",
    "            avg_cost += sess.run(loss,feed_dict=feeds) #loss值\n",
    "        avg_cost = avg_cost/total_batch\n",
    "        if(epoch+1)&display_step == 0:\n",
    "            print('epoch:%03d/%03d loss:%09f'%(epoch,epochs,avg_cost))\n",
    "            feeds={x:batch_xs,y:batch_ys}\n",
    "            train_acc = sess.run(acc,feed_dict=feeds)\n",
    "            print('train acc:%3f'%(train_acc))\n",
    "            feeds = {x:mnist.test.images,y:mnist.test.labels}\n",
    "            test_acc = sess.run(acc,feed_dict=feeds)\n",
    "            print('test acc:%3f'%(test_acc))\n",
    "print('finish')\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
